/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package webResource;

import com.google.gson.Gson;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import model.Booking;
import model.Receipt;

/**
 * REST Web Service
 *
 * @author Jorge
 */
@Path("storage")
public class ServiceStorage {

    @Context
    private UriInfo context;

    /**
     * Creates a new instance of ServiceStorage
     */
    public ServiceStorage() {
    }

    /**
     * Retrieves representation of an instance of webResource.ServiceStorage
     *
     * @return an instance of java.lang.String
     */
    @PUT
    @Consumes("application/json")
    @Produces("application/json")
    public Receipt generateReceipt( Booking booking) {

        Receipt receipt = new Receipt();

        // Generates a random 12-digit receipt code
        char[] receiptChar = new char[12];
        for (int i = 0; i < 12; i++) {
            receiptChar[i] = (char) (48 + (int) (9 * Math.random()));	// Random integer between 48 (0) and 57 (9)
        }
        receipt.setCode(new String(receiptChar));
        receipt.setBooking(booking);

        // Generates a file regarding the receipt
        storeFile(receipt);

        return receipt;

    }

    private void storeFile(Receipt receipt) {
        try {
            // Creates a new file with the contents
            String filename = receipt.getCode() + ".txt";
            File f = new File(filename);
            PrintWriter pw = new PrintWriter(f);
            pw.write(receipt.toString());
            pw.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
